package com.example.myspringtest.utils;

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ContextUtils {

    private static AnnotationConfigServletWebServerApplicationContext applicationContext;

    private ContextUtils() {
    }

    public static void setContext(AnnotationConfigServletWebServerApplicationContext context) {
        applicationContext = context;
    }

    public static AnnotationConfigServletWebServerApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> List<T> listByType(Class<T> clazz) {

        if (Objects.isNull(applicationContext)) {
            return Collections.emptyList();
        }

        return Arrays.stream(applicationContext.getBeanNamesForType(clazz)).map(item -> {
            return (T) applicationContext.getBean(item);
        }).collect(Collectors.toList());
    }


}
